package com.qyhl.module_activities.act.player.newlist;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.reflect.TypeToken;
import com.qyhl.module_activities.R;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.act.PlayerVOBean;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;
import razerdp.basepopup.BasePopupWindow;

public class ActVotePopupWindow extends BasePopupWindow implements ActNewVoteContract.ActNewVoteView {
    private View popupView;
    private List<PlayerBean> mDataList = new ArrayList<>();
    private CommonAdapter commonAdapter;
    private int indexNum = 0;
    private OtherDialog.Builder mDialog;
    private int leftNum = 0;

    private ActNewVotePresenter mPresenter;

    private Activity activity;

    private String actId;

    ActVotePopupWindow(Activity context, String actId, List<PlayerVOBean> dataList, int minNum, int totalNum) {
        super(context);
        mPresenter = new ActNewVotePresenter(this);
        activity = context;
        this.actId = actId;
        bindEvent(dataList, minNum, totalNum);
    }


    @Override
    public View getClickToDismissView() {
        return popupView.findViewById(R.id.click_to_dismiss);
    }

    @SuppressLint("InflateParams")
    @Override
    public View onCreatePopupView() {
        popupView = LayoutInflater.from(getContext()).inflate(R.layout.act_popup_act_vote, null);
        return popupView;
    }

    @Override
    public View initAnimaView() {
        return popupView.findViewById(R.id.popup_anima);
    }

    @SuppressLint("SetTextI18n")
    private void bindEvent(final List<PlayerVOBean> dataList, final int minNum, final int totalNum) {
        if (popupView != null) {
            mDataList.clear();
            for (int i = 0; i < dataList.size(); i++) {
                mDataList.add(new PlayerBean(dataList.get(i).getPlayer().getApplyUrl(), minNum, dataList.get(i).getPlayer().getPlayerName()
                        , dataList.get(i).getVoteNumber(), dataList.get(i).getPlayer().getId()));
            }
            RecyclerView recyclerView = popupView.findViewById(R.id.recycle_view);
            Button commit = popupView.findViewById(R.id.commit_btn);
            Button reset = popupView.findViewById(R.id.reset_btn);
            TextView vote_num = popupView.findViewById(R.id.vote_num);

            vote_num.setText("当前可投票数：" + totalNum);

            leftNum = totalNum - minNum * dataList.size();

            recyclerView.setLayoutManager(new LinearLayoutManager(activity));
            recyclerView.setAdapter(commonAdapter = new CommonAdapter<PlayerBean>(activity, R.layout.act_item_act_player_vote, mDataList) {
                @Override
                protected void convert(ViewHolder holder, final PlayerBean bean, final int position) {
                    ImageView cover = holder.getView(R.id.cover);
                    Glide.with(activity)
                            .load(bean.getCover())
                            .apply(new RequestOptions().placeholder(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                            .into(cover);

                    holder.setText(R.id.name, bean.getName());

                    holder.setText(R.id.vote_num, "当前票数" + bean.getCurNum() + "票");

                    final TextView addBtn = holder.getView(R.id.add_btn);
                    TextView minusBtn = holder.getView(R.id.minus_btn);
                    final TextView num = holder.getView(R.id.num);

                    num.setText(String.valueOf(bean.getNumber()));

                    if (bean.getNumber() <= minNum) {
                        minusBtn.setEnabled(false);
                    } else {
                        minusBtn.setEnabled(true);
                    }

                    if (leftNum <= 0) {
                        addBtn.setEnabled(false);
                    } else {
                        addBtn.setEnabled(true);
                    }

                    addBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (leftNum > 0) {
                                bean.setNumber(bean.getNumber() + 1);
                                leftNum--;
                                commonAdapter.notifyDataSetChanged();
                            }
                        }
                    });

                    minusBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (bean.getNumber() > minNum) {
                                bean.setNumber(bean.getNumber() - 1);
                                leftNum++;
                                commonAdapter.notifyDataSetChanged();
                            }
                        }
                    });

                    num.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            indexNum = 0;
                            mDialog = new OtherDialog.Builder(activity)
                                    .setContentView(R.layout.act_dialog_num_pick)
                                    .setCanceledOnTouchOutside(true)
                                    .setText(R.id.num, String.valueOf(bean.getNumber()))
                                    .setOnClickListenerWithoutDismiss(R.id.add_btn, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            indexNum++;
                                            int sum = bean.getNumber() + indexNum;
                                            mDialog.setText(R.id.num, String.valueOf(sum));
                                        }
                                    })
                                    .setOnClickListenerWithoutDismiss(R.id.minus_btn, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            EditText editText = mDialog.getView().findViewById(R.id.num);
                                            if (StringUtils.isNotEmpty(editText.getText().toString()) && Integer.parseInt(editText.getText().toString()) > 0) {
                                                indexNum--;
                                                int sum = bean.getNumber() + indexNum;
                                                mDialog.setText(R.id.num, String.valueOf(sum));
                                            }
                                        }
                                    })
                                    .setOnClickListenerWithoutDismiss(R.id.commit, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            EditText editText = mDialog.getView().findViewById(R.id.num);
                                            try {
                                                indexNum = Integer.parseInt(editText.getText().toString()) - bean.getNumber();
                                            } catch (Exception e) {
                                                indexNum = 0;
                                            }
                                            if (indexNum > leftNum) {
                                                Toasty.normal(activity, "剩余票数不足！", Toast.LENGTH_LONG).show();
                                                num.setText(String.valueOf(bean.getNumber() + leftNum));
                                                bean.setNumber(bean.getNumber() + leftNum);
                                                leftNum = 0;
                                                commonAdapter.notifyDataSetChanged();
                                            } else {
                                                if (StringUtils.isNotEmpty(editText.getText().toString())) {
                                                    if (Integer.parseInt(editText.getText().toString()) >= minNum) {
                                                        num.setText(String.valueOf(bean.getNumber() + indexNum));
                                                        leftNum = leftNum - indexNum;
                                                        bean.setNumber(bean.getNumber() + indexNum);
                                                    } else {
                                                        Toasty.normal(activity, "至少投" + minNum + "票", Toast.LENGTH_LONG).show();
                                                        indexNum = 0;
                                                        leftNum = leftNum - indexNum;
                                                        bean.setNumber(minNum);
                                                    }
                                                    commonAdapter.notifyDataSetChanged();
                                                }
                                            }

                                            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                                            if (inputMethodManager != null) {
                                                inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                                            }
                                            mDialog.dismiss();
                                        }
                                    });

                            mDialog.show();
                        }
                    });

                }
            });

            commit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (leftNum == 0) {
                        String userName = CommonUtils.getInstance().getUserName();
                        List<upLoadPlayerBean> list = new ArrayList<>();
                        for (int i = 0; i < mDataList.size(); i++) {
                            list.add(new upLoadPlayerBean(mDataList.get(i).getId(), mDataList.get(i).getNumber()));
                        }

                        JsonArray voteData = new Gson().toJsonTree(list, new TypeToken<List<upLoadPlayerBean>>() {
                        }.getType()).getAsJsonArray();
                        mPresenter.doVote(actId, userName, voteData);

                    } else {
                        Toasty.normal(activity, "请将所有票全部投完！").show();
                    }

                }
            });

            reset.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDataList.clear();
                    for (int i = 0; i < dataList.size(); i++) {
                        mDataList.add(new PlayerBean(dataList.get(i).getPlayer().getApplyUrl(), minNum, dataList.get(i).getPlayer().getPlayerName()
                                , dataList.get(i).getVoteNumber(), dataList.get(i).getPlayer().getId()));
                    }
                    leftNum = totalNum - dataList.size() * minNum;
                    commonAdapter.notifyDataSetChanged();
                }
            });
        }
    }


    @Override
    protected Animation initShowAnimation() {
        return getTranslateVerticalAnimation(1f, 0);
    }

    @Override
    protected Animation initExitAnimation() {
        return getTranslateVerticalAnimation(0, 1f);
    }

    /**
     * 生成TranslateAnimation
     *
     * @param start 初始位置
     */
    private static Animation getTranslateVerticalAnimation(float start, float end) {
        Animation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, start, Animation.RELATIVE_TO_PARENT, end);
        translateAnimation.setDuration(500);
        return translateAnimation;
    }

    @Override
    public void onVoteError(String string) {
        Toasty.normal(activity, string).show();
        dismiss();
    }

    @Override
    public void onVoteSuccess(String coin) {
        if (coin.equals("no_coin")) {
            new OtherDialog.Builder(activity)
                    .setWidth(0.8f)
                    .setContentView(R.layout.act_dialog_vote_success)
                    .setCanceledOnTouchOutside(false)
                    .setDismissButton(R.id.cancel)
                    .show();
        } else {
            new OtherDialog.Builder(activity)
                    .setContentView(R.layout.act_dialog_vote_coin_success)
                    .setWidth(1.0f)
                    .setCanceledOnTouchOutside(false)
                    .setText(R.id.coin_txt, "恭喜你，获得" + coin + "金币")
                    .setDismissButton(R.id.cancel)
                    .setOnClickListener(R.id.exchange, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            RouterManager.router(ARouterPathConstant.EXCHANGE_GOLD);
                        }
                    })
                    .show();
        }
        BusFactory.getBus().post(new Event.PlayerListRefresh());
        dismiss();
    }

    class upLoadPlayerBean implements Serializable {
        private int playerId;
        private int number;

        upLoadPlayerBean(int playerId, int number) {
            this.playerId = playerId;
            this.number = number;
        }

        public int getPlayerId() {
            return playerId;
        }

        public void setPlayerId(int playerId) {
            this.playerId = playerId;
        }

        public int getNumber() {
            return number;
        }

        public void setNumber(int number) {
            this.number = number;
        }
    }

    class PlayerBean implements Serializable {
        private String cover;
        private int number;
        private String name;
        private int curNum;
        private int id;

        PlayerBean(String cover, int number, String name, int curNum, int id) {
            this.cover = cover;
            this.number = number;
            this.name = name;
            this.curNum = curNum;
            this.id = id;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getCover() {
            return cover;
        }

        public void setCover(String cover) {
            this.cover = cover;
        }

        public int getNumber() {
            return number;
        }

        public void setNumber(int number) {
            this.number = number;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getCurNum() {
            return curNum;
        }

        public void setCurNum(int curNum) {
            this.curNum = curNum;
        }
    }
}
